﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace FleetServerManager
{
	public class Server
	{
		public static Object _lockObject = new Object();
		public Server()
		{
		}

		public void CreateListener()
		{
			TcpListener listener = null;
			// Make this configurable.
			IPAddress ipAddress = Dns.GetHostEntry("localhost").AddressList[0];

			try
			{
				listener = new TcpListener(ipAddress, 13); // Daytime TCP/UDP port :|
				listener.Start();
				Console.WriteLine("Waiting for connection...");
			}
			catch(Exception e)
			{
				Console.WriteLine(string.Format("Error: {0}", e.ToString()));
			}

			ListenForInput(listener);

		}

		private void ListenForInput(TcpListener listener)
		{
			while (true)
			{
				Thread.Sleep(10);

				//Optional: Socket socket = listener.AcceptTcpClient();
				TcpClient client = listener.AcceptTcpClient();

				//read data
				byte[] bytes = new byte[256];

				lock (_lockObject)
				{
					NetworkStream stream = client.GetStream();
					stream.Read(bytes, 0, bytes.Length);

					//read the stream.
					SocketHelper helper = new SocketHelper();
					helper.ProcessMessage(client, stream, bytes);
				}

			}
		}
	}
}
